package com.example.administrator.schoolblog;

import android.content.ClipData;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;


import com.ashokvarma.bottomnavigation.BadgeItem;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.bumptech.glide.Glide;
import com.example.administrator.schoolblog.Adpater.MainUserContentAdapter;
import com.example.administrator.schoolblog.Beans.BlogUser;
import com.example.administrator.schoolblog.Beans.MainUserContent;
import com.example.administrator.schoolblog.Beans.UserContent;
import com.nightonke.boommenu.BoomButtons.HamButton;
import com.nightonke.boommenu.BoomButtons.OnBMClickListener;
import com.nightonke.boommenu.BoomMenuButton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends BaseActivity {
    private DrawerLayout mainDrawerLayout;
    private NavigationView navigationView;
    private Toolbar toolbar;
    private ActionBarDrawerToggle toggle;
    private String nickname,title,userIconId,contentImageId,userId,contentId;
    private List<MainUserContent> mainUserContentList = new ArrayList<>();
    private MainUserContent mainUserContent;
    private MainUserContentAdapter mainUserContentAdapter;
    private BmobQuery<BlogUser> blogUserBmobQuery;
    private SwipeRefreshLayout swipeRefreshLayout;
    private BottomNavigationBar bottom_navigation_bar;
    private View headerView;
    private CircleImageView user_ic;
    private BlogUser userInfo;
    private long exitTime = 0;
    private BadgeItem badge;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }
        setContentView(R.layout.activity_main);
        Bmob.initialize(this,"b5d62a501dc94902d3f8672a1b5fc2ab","Bmob");
        initView();
        initMainUserContents();
    }

    /**
     * 初始化视图
     */
    private void initView(){
        Intent intent = getIntent();
        userId = intent.getStringExtra("UserId");
        toolbar = (Toolbar) findViewById(R.id.blog_toolbar);
        setSupportActionBar(toolbar);
        mainDrawerLayout = (DrawerLayout) findViewById(R.id.blog_main_drawer);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        navigationView = (NavigationView) findViewById(R.id.blog_naview_main);
        navigationView.setItemIconTintList(null);
        toggle = new ActionBarDrawerToggle(this,mainDrawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        mainDrawerLayout.setDrawerListener(toggle);
        toggle.syncState();
        BoomMenuButton bmb = (BoomMenuButton) findViewById(R.id.bmb);
        for (int i = 0; i < bmb.getPiecePlaceEnum().pieceNumber(); i++) {
            if(i==0){
                HamButton.Builder builder = new HamButton.Builder()
                        .listener(new OnBMClickListener() {
                            @Override
                            public void onBoomButtonClick(int index) {
                                Intent tucao_intent = new Intent(MainActivity.this,TucaoActivity.class);
                                tucao_intent.putExtra("UserId",userId);
                                startActivity(tucao_intent);
                            }
                        })
                        .normalImageRes(R.drawable.blog_main_tucao)
                        .normalTextRes(R.string.blog_main_tucao_text)
                        .subNormalTextRes(R.string.blog_main_sub_tucao_text);
                bmb.addBuilder(builder);
            }else if(i==1){
                HamButton.Builder builder = new HamButton.Builder()
                        .normalImageRes(R.drawable.blog_main_dongtai)
                        .normalTextRes(R.string.blog_main_dongtai_text)
                        .subNormalTextRes(R.string.blog_main_sub_dongtai_text);
                bmb.addBuilder(builder);
            }else{
                HamButton.Builder builder = new HamButton.Builder()
                        .normalImageRes(R.drawable.blog_main_blog)
                        .normalTextRes(R.string.blog_main_blog_text)
                        .subNormalTextRes(R.string.blog_main_sub_blog_text);
                bmb.addBuilder(builder);
            }
        }
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.blog_main_swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshMainUserContent();
            }
        });
        initBottomNavigationBar();
        //头像点击
        headerView = navigationView.inflateHeaderView(R.layout.blog_nav_header);
        user_ic = (CircleImageView) headerView.findViewById(R.id.blog_user_icon);
        BmobQuery<BlogUser> getUser = new BmobQuery<BlogUser>();
        getUser.getObject(userId, new QueryListener<BlogUser>() {
            @Override
            public void done(BlogUser blogUser, BmobException e) {
                if(e==null){
                    if (blogUser.getUserIconUrl()!=null){
                        Glide.with(MainActivity.this).load(blogUser.getUserIconUrl()).into(user_ic);
                    }
                }else {
                    Toast.makeText(MainActivity.this, "获取个人信息失败!", Toast.LENGTH_SHORT).show();
                }
            }
        });
        user_ic.setOnClickListener(new OnClickListener());
    }
    public class OnClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.blog_user_icon:
                    Intent intent = new Intent(MainActivity.this,UserinfoActivity.class);
                    intent.putExtra("UserId",userId);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    }
    /**
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){
            case android.R.id.home:
                mainDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.blog_setting:
                Intent intent = new Intent(MainActivity.this,UserinfoActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }
    /**
     * 初始化首页内容信息
     */
    private void initMainUserContents(){
        mainUserContentList.clear();
        /*for(int i=0;i<10;i++){
            Random random = new Random();
            int index = random.nextInt(mainUserContents.length);
            mainUserContentList.add(mainUserContents[index]);
        }*/
        BmobQuery<UserContent> userContentBmobQuery= new BmobQuery<UserContent>();
        userContentBmobQuery.findObjects(new FindListener<UserContent>() {
            @Override
            public void done(List<UserContent> list, BmobException e) {
                if(e==null){
                    //int i = 0;
                    for (UserContent userContent : list){
                        title = userContent.getTitle();
                        nickname = userContent.getUserNickname();
                        userIconId = userContent.getUserIconUrl();
                        contentImageId = userContent.getCoverUrl();
                        mainUserContent = new MainUserContent(userIconId,nickname,title,contentImageId);
                        mainUserContent.setContentId(userContent.getObjectId());
                        mainUserContent.setUserId(userContent.getUserId());
                        mainUserContentList.add(mainUserContent);
                        RecyclerView mrecyclerView = (RecyclerView) findViewById(R.id.blog_main_recycle);
                        GridLayoutManager layoutManager = new GridLayoutManager(MainActivity.this,1);
                        mrecyclerView.setLayoutManager(layoutManager);
                        mainUserContentAdapter = new MainUserContentAdapter(mainUserContentList);
                        mrecyclerView.setAdapter(mainUserContentAdapter);
                    }
                }
            }
        });
    }
    /**
     * 页面刷新函数
     */
    private void refreshMainUserContent(){
        initMainUserContents();
        mainUserContentAdapter.notifyDataSetChanged();
        swipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 初始化底部导航
     */
    private void initBottomNavigationBar() {
        //控件地址：http://www.jianshu.com/p/134d7847a01e
        bottom_navigation_bar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        bottom_navigation_bar.setMode(BottomNavigationBar.MODE_SHIFTING);
        bottom_navigation_bar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_RIPPLE);
        //设置默认颜色
        bottom_navigation_bar
                .setInActiveColor(R.color.light_grey)//设置未选中的Item的颜色，包括图片和文字
                .setActiveColor(R.color.white)
                .setBarBackgroundColor(R.color.colorPrimary);//设置整个控件的背景色
        //设置徽章
   //     badge=new BadgeItem()
//                .setBorderWidth(2)//Badge的Border(边界)宽度
//                .setBorderColor("#FF0000")//Badge的Border颜色
//                .setBackgroundColor("#9ACD32")//Badge背景颜色
//                .setGravity(Gravity.RIGHT| Gravity.TOP)//位置，默认右上角
//                .setText("2")//显示的文本
//                .setTextColor("#F0F8FF")//文本颜色
//                .setAnimationDuration(2000)
//                .setHideOnSelect(true)//当选中状态时消失，非选中状态显示
        ;
        //添加选项
        bottom_navigation_bar.addItem(new BottomNavigationItem(R.drawable.blog_main_home, "主页"))
                .addItem(new BottomNavigationItem(R.drawable.blog_main_zhuanlan, "专栏"))
                .addItem(new BottomNavigationItem(R.drawable.blog_main_message, "私信"))
                .addItem(new BottomNavigationItem(R.drawable.blog_main_team, "社团"))
                .initialise();//初始化BottomNavigationButton,所有设置需在调用该方法前完成
        bottom_navigation_bar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {//未选中 -> 选中
            }

            @Override
            public void onTabUnselected(int position) {//选中 -> 未选中
            }

            @Override
            public void onTabReselected(int position) {//选中 -> 选中
            }
        });

    }
    /**
     * 退出函数
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                ActivityManager.finishAll();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
